<template>
    <div class="question-form">
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="formRules" 
        label-width="120px"
        @submit.prevent
      >
        <!-- 基本信息 -->
        <el-card class="form-section" header="基本信息">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="题目编号" prop="questionKey">
                <el-input 
                  v-model="formData.questionKey" 
                  placeholder="请输入题目唯一标识"
                  :disabled="!!question"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="题目类型" prop="questionType">
                <el-select 
                  v-model="formData.questionType" 
                  placeholder="请选择题目类型"
                  style="width: 100%"
                  @change="handleTypeChange"
                >
                  <el-option label="单选题" value="single_choice" />
                  <el-option label="多选题" value="multiple_choice" />
                  <el-option label="判断题" value="true_false" />
                  <el-option label="填空题" value="fill_blank" />
                  <el-option label="代码题" value="code" />
                  <el-option label="问答题" value="essay" />
                  <el-option label="拖拽题" value="drag_drop" />
                  <el-option label="匹配题" value="match" />
                  <el-option label="排序题" value="sort" />
                  <el-option label="项目题" value="project" />
                  <el-option label="交互题" value="interactive" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-form-item label="题目标题" prop="questionTitle">
            <el-input 
              v-model="formData.questionTitle" 
              placeholder="请输入题目标题"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
  
          <el-form-item label="题目内容" prop="questionContent">
            <QuillEditor 
              v-model="formData.questionContent"
              placeholder="请输入题目详细内容，支持富文本编辑"
              style="height: 200px"
            />
          </el-form-item>
  
          <el-form-item label="题目图片">
            <el-upload
              class="image-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              :on-success="handleImageSuccess"
            >
              <img v-if="formData.questionImage" :src="formData.questionImage" class="uploaded-image" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-card>
  
        <!-- 题目设置 -->
        <el-card class="form-section" header="题目设置">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-form-item label="难度等级" prop="difficultyLevel">
                <el-rate 
                  v-model="formData.difficultyLevel" 
                  :max="5"
                  show-text
                  :texts="['1星', '2星', '3星', '4星', '5星']"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="题目分值" prop="points">
                <el-input-number 
                  v-model="formData.points" 
                  :min="1"
                  :max="100"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="奖励积分" prop="rewardPoints">
                <el-input-number 
                  v-model="formData.rewardPoints" 
                  :min="1"
                  :max="1000"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="答题时间限制" prop="timeLimit">
                <el-input-number 
                  v-model="formData.timeLimit" 
                  :min="10"
                  :max="7200"
                  controls-position="right"
                  style="width: 100%"
                />
                <span class="form-tip">单位：秒</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="来源类型" prop="sourceType">
                <el-select v-model="formData.sourceType" style="width: 100%">
                  <el-option label="手动录入" value="manual" />
                  <el-option label="批量导入" value="import" />
                  <el-option label="AI生成" value="ai" />
                  <el-option label="面试题库" value="interview" />
                  <el-option label="格式转换" value="convert" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
  
        <!-- 答案设置 -->
        <el-card class="form-section" header="答案设置">
          <!-- 单选题 -->
          <div v-if="formData.questionType === 'single_choice'">
            <el-form-item label="选项设置" prop="options">
              <div class="options-container">
                <div 
                  v-for="(option, index) in formData.options" 
                  :key="index"
                  class="option-item"
                >
                  <el-radio 
                    v-model="formData.correctAnswer"
                    :value="option.key"
                    style="margin-right: 12px"
                  />
                  <el-input 
                    v-model="option.key"
                    placeholder="选项标识"
                    style="width: 80px; margin-right: 12px"
                    maxlength="1"
                  />
                  <el-input 
                    v-model="option.text"
                    placeholder="请输入选项内容"
                    style="flex: 1; margin-right: 12px"
                  />
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeOption(index)"
                    :disabled="formData.options.length <= 2"
                  >
                    删除
                  </el-button>
                </div>
                <el-button type="primary" plain @click="addOption">添加选项</el-button>
              </div>
            </el-form-item>
          </div>
  
          <!-- 多选题 -->
          <div v-if="formData.questionType === 'multiple_choice'">
            <el-form-item label="选项设置" prop="options">
              <div class="options-container">
                <div 
                  v-for="(option, index) in formData.options" 
                  :key="index"
                  class="option-item"
                >
                  <el-checkbox 
                    v-model="formData.correctAnswer"
                    :value="option.key"
                    style="margin-right: 12px"
                  />
                  <el-input 
                    v-model="option.key"
                    placeholder="选项标识"
                    style="width: 80px; margin-right: 12px"
                    maxlength="1"
                  />
                  <el-input 
                    v-model="option.text"
                    placeholder="请输入选项内容"
                    style="flex: 1; margin-right: 12px"
                  />
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeOption(index)"
                    :disabled="formData.options.length <= 2"
                  >
                    删除
                  </el-button>
                </div>
                <el-button type="primary" plain @click="addOption">添加选项</el-button>
              </div>
            </el-form-item>
          </div>
  
          <!-- 判断题 -->
          <div v-if="formData.questionType === 'true_false'">
            <el-form-item label="正确答案" prop="correctAnswer">
              <el-radio-group v-model="formData.correctAnswer">
                <el-radio :value="true">正确</el-radio>
                <el-radio :value="false">错误</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
  
          <!-- 填空题 -->
          <div v-if="formData.questionType === 'fill_blank'">
            <el-form-item label="正确答案" prop="correctAnswer">
              <div class="fill-blank-answers">
                <div 
                  v-for="(answer, index) in formData.correctAnswer" 
                  :key="index"
                  class="blank-answer-item"
                >
                  <el-input 
                    v-model="formData.correctAnswer[index]"
                    :placeholder="`第${index + 1}个空的答案`"
                    style="margin-right: 12px"
                  />
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeBlankAnswer(index)"
                    :disabled="formData.correctAnswer.length <= 1"
                  >
                    删除
                  </el-button>
                </div>
                <el-button type="primary" plain @click="addBlankAnswer">添加填空</el-button>
              </div>
            </el-form-item>
          </div>
  
          <!-- 代码题 -->
          <div v-if="formData.questionType === 'code'">
            <el-form-item label="编程语言" prop="programming_language">
              <el-select v-model="formData.programming_language" style="width: 200px">
                <el-option label="JavaScript" value="javascript" />
                <el-option label="Python" value="python" />
                <el-option label="Java" value="java" />
                <el-option label="C++" value="cpp" />
                <el-option label="C#" value="csharp" />
                <el-option label="Go" value="go" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="代码模板" prop="code_template">
              <CodeEditor 
                v-model="formData.code_template"
                :language="formData.programming_language"
                placeholder="请输入代码模板"
                style="height: 200px"
              />
            </el-form-item>
            
            <el-form-item label="参考答案" prop="correctAnswer">
              <CodeEditor 
                v-model="formData.correctAnswer"
                :language="formData.programming_language"
                placeholder="请输入参考答案代码"
                style="height: 200px"
              />
            </el-form-item>
          </div>
  
          <!-- 问答题 -->
          <div v-if="formData.questionType === 'essay'">
            <el-form-item label="参考答案" prop="correctAnswer">
              <QuillEditor 
                v-model="formData.correctAnswer"
                placeholder="请输入参考答案"
                style="height: 200px"
              />
            </el-form-item>
          </div>
  
          <el-form-item label="答案解析">
            <QuillEditor 
              v-model="formData.answerAnalysis"
              placeholder="请输入答案解析"
              style="height: 150px"
            />
          </el-form-item>
  
          <el-form-item label="提示信息">
            <el-input 
              v-model="formData.hint"
              type="textarea"
              :rows="3"
              placeholder="请输入提示信息（可选）"
            />
          </el-form-item>
        </el-card>
  
        <!-- 标签设置 -->
        <el-card class="form-section" header="标签设置">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="知识点标签">
                <el-select 
                  v-model="formData.knowledgePoints"
                  multiple
                  filterable
                  allow-create
                  placeholder="请选择或输入知识点标签"
                  style="width: 100%"
                >
                  <el-option 
                    v-for="tag in knowledgePointTags"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="技能标签">
                <el-select 
                  v-model="formData.skillTags"
                  multiple
                  filterable
                  allow-create
                  placeholder="请选择或输入技能标签"
                  style="width: 100%"
                >
                  <el-option 
                    v-for="tag in skillTags"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
  
      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button @click="handlePreview">预览</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
  
      <!-- 预览对话框 -->
      <el-dialog v-model="showPreview" title="题目预览" width="60%">
        <QuestionPreview :question="previewData" />
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, watch, computed, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
//   import QuillEditor from '@/components/QuillEditor.vue'
//   import CodeEditor from '@/components/CodeEditor.vue'
  import QuestionPreview from './QuestionPreview.vue'
  
  const props = defineProps({
    question: {
      type: Object,
      default: null
    },
    nodeId: {
      type: [String, Number],
      required: true
    }
  })
  
  const emit = defineEmits(['submit', 'cancel'])
  
  // 表单引用
  const formRef = ref(null)
  const showPreview = ref(false)
  
  // 表单数据
  const formData = reactive({
    questionKey: '',
    questionType: 'single_choice',
    questionTitle: '',
    questionContent: '',
    questionImage: '',
    difficultyLevel: 1,
    points: 10,
    rewardPoints: 10,
    timeLimit: 60,
    sourceType: 'manual',
    correctAnswer: '',
    answerAnalysis: '',
    hint: '',
    knowledgePoints: [],
    skillTags: [],
    options: [
      { key: 'A', text: '' },
      { key: 'B', text: '' }
    ],
    programming_language: 'javascript',
    code_template: ''
  })
  
  // 预览数据
  const previewData = computed(() => {
    return {
      ...formData,
      node_id: props.nodeId
    }
  })
  
  // 表单验证规则
  const formRules = {
    questionKey: [
      { required: true, message: '请输入题目编号', trigger: 'blur' }
    ],
    questionType: [
      { required: true, message: '请选择题目类型', trigger: 'change' }
    ],
    questionTitle: [
      { required: true, message: '请输入题目标题', trigger: 'blur' }
    ],
    questionContent: [
      { required: true, message: '请输入题目内容', trigger: 'blur' }
    ],
    difficultyLevel: [
      { required: true, message: '请选择难度等级', trigger: 'change' }
    ],
    points: [
      { required: true, message: '请输入题目分值', trigger: 'blur' }
    ]
  }
  
  // 标签选项
  const knowledgePointTags = ref([
    'JavaScript基础', 'Vue.js', 'React', 'HTML', 'CSS', '算法', '数据结构'
  ])
  
  const skillTags = ref([
    '逻辑思维', '代码阅读', '问题分析', '设计模式', '性能优化'
  ])
  
  // 上传配置
  const uploadAction = '/api/upload/image'
  
  // 初始化表单数据
  const initFormData = () => {
    if (props.question) {
      Object.assign(formData, props.question)
      
      // 处理选择题选项
      if (formData.questionType === 'single_choice' || formData.questionType === 'multiple_choice') {
        if (typeof formData.correctAnswer === 'string') {
          try {
            const parsed = JSON.parse(formData.correctAnswer)
            if (parsed.options) {
              formData.options = parsed.options
              formData.correctAnswer = parsed.answer
            }
          } catch (e) {
            console.error('解析答案失败', e)
          }
        }
      }
    } else {
      // 生成默认题目编号
      formData.questionKey = generateQuestionKey()
    }
  }
  
  // 生成题目编号
  const generateQuestionKey = () => {
    const timestamp = Date.now().toString().slice(-6)
    return `Q${timestamp}`
  }
  
  // 题目类型变化处理
  const handleTypeChange = (type) => {
    // 重置答案相关字段
    switch (type) {
      case 'single_choice':
        formData.correctAnswer = 'A'
        formData.options = [
          { key: 'A', text: '' },
          { key: 'B', text: '' }
        ]
        break
      case 'multiple_choice':
        formData.correctAnswer = []
        formData.options = [
          { key: 'A', text: '' },
          { key: 'B', text: '' }
        ]
        break
      case 'true_false':
        formData.correctAnswer = true
        break
      case 'fill_blank':
        formData.correctAnswer = ['']
        break
      default:
        formData.correctAnswer = ''
    }
  }
  
  // 选项操作
  const addOption = () => {
    const nextKey = String.fromCharCode(65 + formData.options.length)
    formData.options.push({
      key: nextKey,
      text: ''
    })
  }
  
  const removeOption = (index) => {
    formData.options.splice(index, 1)
    // 重新分配选项标识
    formData.options.forEach((option, idx) => {
      option.key = String.fromCharCode(65 + idx)
    })
  }
  
  // 填空答案操作
  const addBlankAnswer = () => {
    formData.correctAnswer.push('')
  }
  
  const removeBlankAnswer = (index) => {
    formData.correctAnswer.splice(index, 1)
  }
  
  // 图片上传
  const beforeImageUpload = (file) => {
    const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
    const isLt2M = file.size / 1024 / 1024 < 2
  
    if (!isValidType) {
      ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('上传图片大小不能超过 2MB!')
      return false
    }
    return true
  }
  
  const handleImageSuccess = (response) => {
    formData.questionImage = response.data.url
    ElMessage.success('图片上传成功')
  }
  
  // 表单操作
  const handleSubmit = async () => {
    try {
      await formRef.value.validate()
      
      // 处理答案数据
      const submitData = { ...formData }
      
      if (submitData.questionType === 'single_choice' || submitData.questionType === 'multiple_choice') {
        submitData.correctAnswer = JSON.stringify({
          options: submitData.options,
          answer: submitData.correctAnswer
        })
      } else if (Array.isArray(submitData.correctAnswer)) {
        submitData.correctAnswer = JSON.stringify(submitData.correctAnswer)
      }
      
      emit('submit', submitData)
    } catch (error) {
      ElMessage.error('请检查表单填写是否完整')
    }
  }
  
  const handleCancel = () => {
    emit('cancel')
  }
  
  const handlePreview = () => {
    showPreview.value = true
  }
  
  // 检查是否有未保存的更改
  const hasUnsavedChanges = () => {
    // 简单的检查逻辑，实际项目中可能需要更复杂的比较
    return formData.questionTitle.trim() !== '' || formData.questionContent.trim() !== ''
  }
  
  // 暴露方法给父组件
  defineExpose({
    hasUnsavedChanges
  })
  
  // 初始化
  onMounted(() => {
    initFormData()
  })
  
  // 监听props变化
  watch(() => props.question, () => {
    initFormData()
  }, { immediate: true })
  </script>
  
  <style scoped>
  .question-form {
    max-width: 1200px;
  }
  
  .form-section {
    margin-bottom: 20px;
  }
  
  .form-section :deep(.el-card__header) {
    background-color: #f8f9fa;
    font-weight: 600;
  }
  
  .options-container {
    width: 100%;
  }
  
  .option-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
  }
  
  .fill-blank-answers {
    width: 100%;
  }
  
  .blank-answer-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
  }
  
  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-left: 8px;
  }
  
  .image-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
  }
  
  .image-uploader:hover {
    border-color: #409eff;
  }
  
  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .uploaded-image {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
  }
  
  .form-actions {
    text-align: center;
    padding: 20px 0;
    border-top: 1px solid #ebeef5;
    margin-top: 20px;
  }
  
  .form-actions .el-button {
    margin: 0 8px;
    min-width: 80px;
  }
  
  :deep(.el-rate) {
    display: flex;
    align-items: center;
  }
  
  :deep(.el-rate__text) {
    margin-left: 8px;
  }
  </style>